//
//  AccountViewController.m
//  bitcoin
//
//  Created by caiyajun on 2018/5/25.
//  Copyright © 2018年 比特币. All rights reserved.
//

#import "AccountViewController.h"
#import "AccountCapitalCell.h"
#import "AccountModel.h"

#import "MJRefresh.h"
#import "XTNetReloader.h"
#import "WeChatStylePlaceHolder.h"

#import "PromptView.h"

#import "RecordTableViewController.h"
@interface AccountViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet UITableView *contentTableView;
@property (weak, nonatomic) IBOutlet UIButton *eyeBtn;
@property (weak, nonatomic) IBOutlet UILabel *btcLabel;
@property (weak, nonatomic) IBOutlet UILabel *cnfLabel;
@property (weak, nonatomic) IBOutlet UISearchBar *searchKindBar;
@property (weak, nonatomic) IBOutlet UIButton *hideSmallBtn;

@property (nonatomic, copy) NSString *btc;
@property (nonatomic, copy) NSString *USDT;
@property (nonatomic, copy) NSString *CNY;
@property (nonatomic, copy) NSString *NZD;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, copy) NSString *moneyKind;


@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) MJRefreshAutoNormalFooter *footer;
@property (nonatomic, strong) MJRefreshAutoNormalFooter *nilFooter;
@end

@implementation AccountViewController
- (NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.page=1;
    
    [_eyeBtn setImage:[UIImage imageNamed:@"open-icon-1"] forState:UIControlStateNormal];
    [_eyeBtn setImage:[UIImage imageNamed:@"close-icon-2"] forState:UIControlStateSelected];
    
    [_hideSmallBtn setImage:[UIImage imageNamed:@"hide-icon"] forState:UIControlStateNormal];
    [_hideSmallBtn setImage:[UIImage imageNamed:@"show-icon"] forState:UIControlStateSelected];
    self.contentTableView.delegate=self;
    self.contentTableView.dataSource=self;
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrowleft-icon"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    self.navigationItem.leftBarButtonItem = back;
    
    UIImage* searchBarBg = [self GetImageWithColor:[UIColor clearColor] andHeight:32.0f];
    //设置背景图片
    [_searchKindBar setBackgroundImage:searchBarBg];
    //设置背景色
    [_searchKindBar setBackgroundColor:[UIColor clearColor]];
    //设置文本框背景
    [_searchKindBar setSearchFieldBackgroundImage:searchBarBg forState:UIControlStateNormal];

    UITextField *searchField=[_searchKindBar valueForKey:@"_searchField"];
    searchField.backgroundColor = [UIColor clearColor];
    searchField.textColor=[UIColor whiteColor];
    [searchField setValue:RGBColor(153, 153, 153) forKeyPath:@"_placeholderLabel.textColor"];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, ScreenWidth, 40.0)];
    button.backgroundColor = [UIColor whiteColor];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitle:@"取消" forState:UIControlStateNormal];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 20);
    [button addTarget:self action:@selector(hiddenKeyboard) forControlEvents:UIControlEventTouchUpInside];
    _searchKindBar.inputAccessoryView = button;
    _searchKindBar.delegate = self;
    
    

    
}
- (UIImage*) GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height {
    CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
    UIGraphicsBeginImageContext(r.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, r);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
    return img;
    
}



- (void)beginToRequestData{
    self.page++;
    [self requstData];
}
- (void)backAction:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillAppear:(BOOL)animated{
    [self requstMoneyData];
    [self requstData];
}
-(void)requstMoneyData{
    
    [LSRequestManager getRequestWithURL:HUOBI(@"api/currency/myAccount")
                                  params:nil
                                 success:^(NSDictionary *responseData) {
                                     if ([responseData[@"ret"] integerValue ] == 0) {
                                         self.btc=[NSString stringWithFormat:@"%@",responseData[@"data"][@"totalAmountBTC"]];
                                         self.USDT=[NSString stringWithFormat:@"%@",responseData[@"data"][@"totalAmountUSD"]];
                                         self.NZD=[NSString stringWithFormat:@"%@",responseData[@"data"][@"totalAmountAUD"]];
                                         self.CNY=[NSString stringWithFormat:@"%@",responseData[@"data"][@"totalAmountCNY"]];
                                         
                                         self.btcLabel.text=[NSString stringWithFormat:@"%@",self.btc];
                                         if ([[UserDefaults objectForKey:K_PRICE] isEqualToString:@"1"]){
                                             self.cnfLabel.text=[NSString stringWithFormat:@"≈ %@",self.CNY];
                                         }else if ([[UserDefaults objectForKey:K_PRICE] isEqualToString:@"2"]){
                                             self.cnfLabel.text=[NSString stringWithFormat:@"≈ %@",self.USDT];
                                         }else{
                                             self.cnfLabel.text=[NSString stringWithFormat:@"≈ %@",self.NZD];
                                         }
                                     } else {
                                         self.btc=@"";
                                         self.USDT=@"";
                                         self.NZD=@"";
                                         self.CNY=@"";
                                         self.btcLabel.text=@" BTC";
                                         self.cnfLabel.text=@"≈  AUD";
                                         [MBProgressHUD showError:responseData[@"msg"]];
                                     }
                                 }
                                 failure:^(NSError *error) {
                                     self.btc=@"";
                                     self.USDT=@"";
                                     self.NZD=@"";
                                     self.CNY=@"";
                                     self.btcLabel.text=@" BTC";
                                     self.cnfLabel.text=@"≈  AUD";
                                 }
                                 showHUD:NO];
    
    
    
    
    
    
}
-(void)requstData{
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(beginToRequestData)];
//    [footer setTitle:@"点击或下拉加载更多" forState:MJRefreshStateIdle];
    [footer setTitle:@"加载中" forState:MJRefreshStateRefreshing];
    footer.stateLabel.textColor = RGBColor(153, 153, 153);
    self.footer = footer;
    
    
    
    
    if ([[UserDefaults objectForKey:K_PRICE] isEqualToString:@"2"]){
        self.moneyKind=@"USD";
    }else if ([[UserDefaults objectForKey:K_PRICE] isEqualToString:@"3"]){
        self.moneyKind=@"AUD";
    }else{
        self.moneyKind=@"CNY";
    }
    NSDictionary *param = @{
                            @"search_field" : self.searchKindBar.text?self.searchKindBar.text:@"",
                            @"list_rows" : @"15",
                            @"page" : @(self.page),
                            @"legeal" : self.moneyKind};
    [LSRequestManager getRequestWithURL:HUOBI(@"api/currency/currencyWallet")
                                 params:param
                                success:^(NSDictionary *responseData) {
                                    if ([responseData[@"ret"] integerValue ] == 0) {
                                        if (self.page==1) {
                                            [self.dataSource removeAllObjects];
                                        }
                                        NSArray *array = [AccountModel mj_objectArrayWithKeyValuesArray:responseData[@"data"][@"data"]];
                                        [self.dataSource addObjectsFromArray:array];
                                        if (array.count < 15) {
                                            self.contentTableView.mj_footer = self.nilFooter;
                                        } else {
                                            self.contentTableView.mj_footer = self.footer;
//                                            self.footer.refreshingTitleHidden = YES;
                                        }
                                        [self.contentTableView.mj_footer endRefreshing];
                                        [self.contentTableView reloadData];
                                        
                                    } else {
                                        [MBProgressHUD showError:responseData[@"msg"]];
                                    }
                                }
                                failure:^(NSError *error) {
                                    
                                }
                                showHUD:NO];
    
    
    
    
    
    
    
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    // 点击了搜索按钮
    NSLog(@"点击了搜索按钮");
    
    // 获取搜索输入内容
    NSString *text = searchBar.text;
    NSLog(@"text = %@", text);
    self.page=1;
    [self requstData];
    // 隐藏键盘，即退出编辑
    [self hiddenKeyboard];
}
// 隐藏键盘
- (void)hiddenKeyboard
{
    [self.view endEditing:YES];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    AccountCapitalCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AccountCapitalCell" forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[AccountCapitalCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AccountCapitalCell"];
    }
    AccountModel*accountModel=self.dataSource[indexPath.row];
    cell.amountLabel.text=accountModel.amount;
    cell.forzenLabel.text=accountModel.forzen_amount;
    cell.assessmentLabel.text=accountModel.assessment;
    cell.markLabel.text=accountModel.mark;
    cell.moneyKindLabel.text=[NSString stringWithFormat:@"估算(%@)",self.moneyKind];
    return cell;
    
}

- (CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 105.0f;
}
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{

    AccountModel*accountModel=self.dataSource[indexPath.row];
    [self performSegueWithIdentifier:@"recordSegue" sender:accountModel];
    
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"recordSegue"]){
        RecordTableViewController *recordCtrl = segue.destinationViewController;
        recordCtrl.accountModel = sender;
    }
    
}





- (IBAction)changeEyeAction:(UIButton *)sender {
    if (!sender.selected) {
        self.btcLabel.text=@"*** BTC";
        if ([[UserDefaults objectForKey:K_PRICE] isEqualToString:@"2"]){
            self.cnfLabel.text=@"≈ *** USDT";
        }else if ([[UserDefaults objectForKey:K_PRICE] isEqualToString:@"3"]){
            self.cnfLabel.text=@"≈ *** NZD";
        }else{
            self.cnfLabel.text=@"≈ *** CNY";
        }
    }else{
        self.btcLabel.text=[NSString stringWithFormat:@"%@ BTC",self.btc];
        if ([[UserDefaults objectForKey:K_PRICE] isEqualToString:@"2"]){
            self.cnfLabel.text=[NSString stringWithFormat:@"≈ %@ USDT",self.USDT];
        }else if ([[UserDefaults objectForKey:K_PRICE] isEqualToString:@"3"]){
            self.cnfLabel.text=[NSString stringWithFormat:@"≈ %@ NZD",self.NZD];
        }else{
            self.cnfLabel.text=[NSString stringWithFormat:@"≈ %@ CNY",self.CNY];
        }
        
    }
    sender.selected = !sender.selected;
    
}
- (IBAction)hideSmallAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    
    
    
    
    
    
}
- (IBAction)showAction:(UIButton *)sender {
    
    PromptView *promptView = [PromptView xib];
    [[UIApplication sharedApplication].keyWindow addSubview:promptView];
     __weak typeof(promptView) weakpromptView = promptView;
    promptView.knowActionBlock = ^(NSString*text) {
        
        
        [weakpromptView removeFromSuperview];
    };
    
    
}

@end
